<?php
namespace app\app\controller;
use think\Db;
class Driver extends Common {
    /*     * *
     * 获取司机（酒店管理员）的信息   driver/get_info
     * ** */

    public function get_info(){
        $token = request()->request('token');
        $uid = token_decode($token);
        $msg['state'] = 1;
        $driver = Db::table('user')->field('true_name,money,isExpress,business,express_type,express_cut,true_head')->where('id', $uid)->find();
        //添加了类别以示登陆用户的区别
        $info = [];
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $today_order = 0;
        $today_earning_detail = Db::table('earning')->where(['uid' => $uid, 'time' => ['between', $beginToday . ',' . $endToday], 'type' => 'express'])->select();
        $today_earning = 0;
        foreach ($today_earning_detail as $v){
            $today_order++;
            $today_earning += $v['money'];
        }
        $info['today_order'] = $today_order;//今日订单量
        $info['today_earning'] = strval($today_earning); //今日金钱
        $check = Db::table('express_check')->where('uid', $uid)->order('retime desc')->find();
        if (empty($check)) {
            $info['approve'] = 0; //未认证 默认
        } elseif (count($check > 0)) {
            $info['approve'] = $check['status']; //1认证;2,审核中
        } else {
            $info['approve'] = 3; //已拒绝
        }
        //如果真名为空则默认driver['true_name']
        if (empty($info['true_name'])) {
            $info['true_name'] = $driver['true_name'];
        }
        //如果认证头像没有的话,就以driver中的头像为默认头像
        if (empty($info['true_head'])) {
            $info['true_head'] = $driver['true_head'];
        }

        //金钱或余额
        if (empty($info['money'])) {
            $info['money'] = $driver['money']; //总金额
        }
        $info['express_cut']=$driver['express_cut'];
        $msg['data'] = $info;
        $msg['msg'] = '获取成功';
        return json($msg);
    }

    //传送城市数据 
    public function get_city_list() {
        //三表关联view();的使用view
        $msg['state'] = 1;
        $city = Db::table('area')->field('area.id as aid,area.name as area')->view('city', ['id' => 'cid', 'name' => 'city'], 'city.id=area.father_id', 'LEFT')->view('province', ['province.id' => 'pid', 'name' => 'province'], 'province.id=city.father_id', 'LEFT')->where(['area.status' => 1])->order('area.capital asc')->select();
        $msg['data'] = $city;
        $msg['msg'] = "获取成功";
        return json($msg);
    }

    //司机更新城市 driver/update_address
    public function update_address() {
        $token = request()->request('token');
        $uid = token_decode($token);
        $lng = request()->request('lng');
        $lat = request()->request('lat');
        $province = request()->request('province');
        $city = request()->request('city');
        $area = request()->request('area');
        $data['lng'] = $lng;
        $data['lat'] = $lat;
        if ($province != '' && $city != '' && $area != '') {
            $data['pid'] = Db::table('province')->where('name', 'like', '%' . $province . '%')->value('id');
            $data['cid'] = Db::table('city')->where('name', 'like', '%' . $city . '%')->value('id');
            $data['aid'] = Db::table('area')->where('name', 'like', '%' . $area . '%')->value('id');
        }
        $data['active_time'] = time();
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($lng) || empty($lat)) {
            $msg['msg'] = '经纬度缺失';
        } else {
            $msg['state'] = 1;
            Db::table('user')->where('id', $uid)->update($data);
            $msg['msg'] = '上传成功';
        }
        return json($msg);
    }

    //司机认证  driver/update_express
    public function update_express(){
        $token = request()->request('token');
        $data['uid'] = token_decode($token);
        $data['idcard'] = request()->request('idcard');
        $data['true_name'] = request()->request('true_name');
        $data['ali_number'] = request()->request('ali_number');
        $data['car_number'] = request()->request('car_number');
        $data['pid'] = request()->request('pid');
        $data['cid'] = request()->request('cid');
        $data['aid'] = request()->request('aid');
        $msg['state']=0;
        $msg['data']="";
        if(!$_FILES){
            $msg['msg'] = '请上传手持身份证照片';
         }else{
           $bool = true;
           foreach ($data as $k => $v) {
                if (empty($v)){
                    $bool = false;
                    $msg['msg'] = $k . ' not have';
                    break;
                }
          }
           if($bool){
               $check = Db::table('express_check')->where('uid', $data['uid'])->order('id desc')->find();
                if (count($check) > 0){
                    if($check['status'] == 1){
                        $msg['msg'] = '您已经是司机了，请勿重复申请';
                    }elseif($check['status'] == 2){
                        $msg['msg'] = '您的申请已经在处理中，请耐心等待系统审核';
                    }elseif($check['status'] == 3 || $check['status'] == 0){//被拒绝后可以修改
                        $msg['state'] = 1;
                        $Files = upload();
                        $data['idcard_hand'] = $Files['idcard_hand']['url']; //手持身份证
                        $data['idcard_front'] = $Files['idcard_front']['url']; //身份证正面
                        $data['idcard_back'] = $Files['idcard_back']['url']; //身份证背面
                        $data['true_head'] = $Files['true_head']['url']; //真实头像
                        $data['jiacard_front'] = $Files['jiacard_front']['url']; //驾照正面
                        $data['xingcard_front'] = $Files['xingcard_front']['url']; //行驶证正面
                        $data['car_front'] = $Files['car_front']['url']; //汽车正面照
                        $data['status'] = 2; //审核中
                        $data['retime'] = time();
                        $data['express_type'] = 1; //司机类型
                        Db::table('express_check')->where('uid', $data['uid'])->update($data);
                        Db::table('user')->where('id', $data['uid'])->update(['pid' => $data['pid'], 'cid' => $data['cid'], 'aid' => $data['aid'], 'true_name' => $data['true_name']]);
                        $msg['msg'] = '申请成功，请等待审核';
                    }
                }else{
                    $msg['state'] = 1;
                    $Files = upload();
                    $data['idcard_hand'] = $Files['idcard_hand']['url']; //手持身份证
                    $data['idcard_front'] = $Files['idcard_front']['url']; //身份证正面
                    $data['idcard_back'] = $Files['idcard_back']['url']; //身份证背面
                    $data['true_head'] = $Files['true_head']['url']; //真实头像
                    $data['jiacard_front'] = $Files['jiacard_front']['url']; //驾照正面
                    $data['xingcard_front'] = $Files['xingcard_front']['url']; //行驶证正面
                    $data['car_front'] = $Files['car_front']['url']; //汽车正面照
                    $data['status'] = 2; //审核中
                    $data['retime'] = time();
                    $data['express_type'] = 1; //司机类型
                    Db::table('express_check')->insert($data);
                    Db::table('user')->where('id', $data['uid'])->update(['pid' => $data['pid'], 'cid' => $data['cid'], 'aid' => $data['aid'], 'true_name' => $data['true_name']]);
                    $msg['msg'] = '申请成功，请等待审核';
                }
            }
        }
        return json($msg);
    }

    //司机切换接单状态 driver/set_business
    public function set_business(){
        $token = request()->request('token');
        $uid = token_decode($token);
        $status = request()->request('status');
        $msg['state'] = 0;
        $msg['data'] = $status;
        if ($status == '') {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            Db::table('user')->where('id', $uid)->update(['business' => $status]);
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }

    //发起拼车driver/pin_cart
    public function pin_cart(){
        $token = request()->request('token');
        $uid = token_decode($token);
        $data = [];
        $data['uid'] = $uid;
        $approve = Db::table("user")->where('id', $data['uid'])->value('status');
       if ($approve == '' || $approve !== 1){
            $msg['state'] = 0;
            $msg['msg'] = "请您先认证为司机";
       }else {
        $data['total_count'] = request()->request('total_count'); //总人数    
        $data['place_name'] = request()->request('place_name'); //开始地点
        $data['target_name'] = request()->request('target_name'); //结束地点
        $data['leave_time'] = request()->request('leave_time'); //出发时间
        $data['price'] = request()->request('price'); //行程金额
        $area = Db::table("express_check")->where('uid', $data['uid'])->find();
        $data['pid'] = $area['pid']; //地点关联的目的是为了防止本地区外的司机接客
        $data['cid'] = $area['cid'];
        $data['aid'] = $area['aid'];
        $data['status'] = 3; //进行中
        $data['regtime'] = time();
        Db::table('user_pin')->insert($data); //插入数据库   
        $msg['state'] = 1;
        $msg['msg'] = "success!";
        }
        return json($msg);
    }

    //司机获取自己发起的拼单 driver/get_pin_cate 传token
    public function get_pin_cate(){
        $token = request()->request('token');
        $uid = token_decode($token);
        $approve = Db::table("express_check")->where('uid', $uid)->value('status');
        $cate = [];
        if ($approve == '' || $approve !== 1) {
            $msg['state'] = 0;
            $msg['msg'] = "请您先认证为司机";
        }else {
            $cate = Db::table("user_pin")->field('id,price,total_count,place_name,target_name,leave_time')->where('uid', $uid)->find();
            $count = Db::table("order")->field('count')->where('u_p_id', $cate['id'])->select();
            $title_count = 0; //需要计算的与拼单相关联的订单中的人数
            foreach ($count as $k => $v) {
                $title_count += $v['count'];
            }
            if ($title_count > $cate['total_count']){
                $msg['state'] = 0;
                $msg['msg'] = "error";
            } else {
                $cate['count'] = strval($title_count);
                $msg['data'] = $cate;
                $msg['state'] = 1;
                $msg['msg'] = "success!";
            }
        }
        //返回数据
        return json($msg);
    }

//    //司机获取拼单的详情页
//    public function pin_cate_detail(){
//        $token = request()->request('token');
//        $uid = token_decode($token); //司机的id
//        $u_p_id = request()->request('u_p_id');//拼车列表传来的u_p_id
//        $approve = Db::table("express_check")->where('uid', $uid)->value('status');
//        if ($approve == '' || $approve !== 1){
//            $msg['state'] = 0;
//            $msg['msg'] = "请您先认证为司机";
//        }else{
//            $msg['state'] = 1;
//            $fields = 'total_count,place_name,target_name,leave_time,price';
//            $cate = Db::table("user_pin")->field($fields)->where(['uid' => $uid, 'id' => $u_p_id])->find();
//            $msg['data'] = $cate;
//            $pin_list = Db::view("order", 'uid,place_truename,place_lat,place_lng,u_p_id')->view("user", 'headimg', 'order.uid=user.id')->view("user_pin", 'total_count', 'user_pin.id=order.u_p_id')->where("order.u_p_id", $u_p_id)->select();
//            $msg['data']['pin_list'] = $pin_list;
//            $msg['msg'] = "success";
//        }
//        return json($msg);
//    }

//    //司机获取订单列表(切换状态) 
//     public function get_grab_order_list() {
//        $token = request()->request("token"); //token 
//        $uid = token_decode($token); //司机的uid
//        $status = request()->request("status");
//        $lng = request()->request('lng');
//        $lat = request()->request('lat');
//        $area = request()->request("area");
//        if (!empty($status)) {//状态的更变
//            if ($status == 1) {
//                $where['status'] = ['in', '1']; //新订单
//            } elseif ($status == 2) {
//                $where['status'] = ['in', '2,3,4,5,6']; //进行中
//            } elseif ($status == 3) {
//                $where['status'] = ['in', '7,8,9']; //已完成
//            }
//        }
//        $msg['state'] = 0;
//        $data = [];
//        if (empty($lng) || empty($lat)) {
//            $msg['msg'] = '经纬度缺失';
//        } else {
//            $where['express'] = 0;
//            $msg['state'] = 1;
//            $aid = Db::table('area')->where('name', 'like', '%' . $area . '%')->value('id');
//            $express_config = Db::table('express_config')->where('aid', $aid)->find();
//            $scope = $express_config['scope'];
//            $pi = floatval($this->get_lat_lng($scope));
//            $fields = 'order_id,type,express_charge,place_lng,place_lat,place_address,target_lng,target_lat,target_address,audio,audio_length,status';
//            $express = Db::table('user')->where('id', $uid)->find(); //express_type 司机或酒店管理员的类别  
//            $whereIn = Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type');
//            $whereOr = '(target_lat > ' . $lat . '-' . $pi . ' and target_lat < ' . $lat . '+' . $pi . ' and target_lng > ' . $lng . '-' . $pi . 'and target_lng < ' . $lng . '+' . $pi . ') or (place_lat > ' . $lat . '-' . $pi . ' and place_lat < ' . $lat . '+' . $pi . ' and place_lng > ' . $lng . '-' . $pi . ' and place_lng < ' . $lng . '+' . $pi . ')';
//            $data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->where($whereOr)->whereIn('type', $whereIn)->order('issue_time desc')->select(); //这里主要是根据叫个车和跑个腿来区别新订单
//            $msg['data'] = $data;
//            $msg['msg'] = '获取成功';
//        }
//        return json($msg);
//    }

    //新订单接口
    public function get_new_order_list(){
        $token = request()->request("token");
        $uid = token_decode($token);
        $lng = request()->request('lng');
        $lat = request()->request('lat');
        $area = request()->request("area");
        $where['status'] = ['in', '1']; //新订单
        $msg['state'] = 0;
        $data = [];
        if (empty($lng) || empty($lat)){
            $msg['msg'] = "经纬度缺失";
        }else{
            $where['express'] = 0;//司机未抢单默认值
            $msg['state'] = 1;
            $aid = Db::table('area')->where('name', 'like', '%' . $area . '%')->value('id');
            //aid
            $express_config = Db::table('express_config')->where('aid', $aid)->find();
            //halt($express_config);
            $scope = $express_config['scope'];
            $pi = floatval($this->get_lat_lng($scope));
            $fields = 'order_id,type,express_charge,place_address,target_address,audio,audio_length,status';
            $express = Db::table('user')->where('id', $uid)->find();
           // halt($express);
            $where['aid']=Db::table("express_check")->where(['status'=>1,'uid'=>$uid])->value("aid");
            $whereIn = Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type'); 
       
            $whereOr = '(target_lat > ' . $lat . '-' . $pi . ' and target_lat < ' . $lat . '+' . $pi . ' and target_lng > ' . $lng . '-' . $pi . 'and target_lng < ' . $lng . '+' . $pi . ') or (place_lat > ' . $lat . '-' . $pi . ' and place_lat < ' . $lat . '+' . $pi . ' and place_lng > ' . $lng . '-' . $pi . ' and place_lng < ' . $lng . '+' . $pi . ')';
            //halt($whereOr);
            $data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->where($whereOr)->whereIn('type', $whereIn)->order('issue_time desc')->select();
            //echo Db::table('order')->getLastSql();exit;
            $msg['data'] = $data;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }
    //酒店新订单列表
    public function get_new_book_order_list()
   {
        $token = request()->request("token");
        $uid = token_decode($token);
        $where['status'] = ['in', '1']; //新订单
        $msg['state'] = 0;
        $data = [];
        if(empty($token)){
           $msg['msg']="error:酒店凭证获取失败";
        }else{
         $where['express'] = 0;//司机未抢单默认值   
         $msg['state'] = 1;
         $fields = 'order_id,type,express_charge,place_address,target_address,audio,audio_length,status';
         $express = Db::table('user')->where('id', $uid)->find();
         $where['aid']=Db::table("express_check")->where(['status'=>1,'uid'=>$uid])->value("aid");
         $whereIn = Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type'); 
         $data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->whereIn('type', $whereIn)->order('issue_time desc')->select();
         $msg['data'] = $data;
         $msg['msg'] = '获取成功';   
        }
     return json($msg);  
    }
    
    
    
    //进行中订单列表
    public function get_express_order_list(){
        $token = request()->request("token");
        $uid = token_decode($token); //司机的//酒店的
        if (empty($token)){
            $msg['state'] = 0;
            $msg['msg'] = "token:error";
        } else {
            $where['status'] = ['in', '3,4,5,6,7,8,10'];
            $where['express'] = $uid;
            
            $msg['state'] = 1;
            $fields = 'order_id,type,express_charge,place_address,target_address,audio,audio_length,status';
            $field = 'id as u_p_id,total_count as u_total_count,place_name as u_place_name,target_name as u_target_name,leave_time,count as u_count,price as u_price,status';
            $express = Db::table('user')->where('id', $uid)->find();
            $whereIn = Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type');
            
            $order_data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->whereIn('type', $whereIn)->order('issue_time desc')->select();
            
            foreach ($order_data as $k => $v){
                $order_data[$k]['u_p_id'] = '';
                $order_data[$k]['u_total_count'] = '';
                $order_data[$k]['u_place_name'] = '';
                $order_data[$k]['u_target_name'] = '';
                $order_data[$k]['leave_time'] = '';
                $order_data[$k]['u_count'] = '';
                $order_data[$k]['u_price'] = '';
                $order_data[$k]['status'] = $v['status']; 
            }
            $cate_data = Db::table("user_pin")->field($field)->where(['uid' => $uid, 'status' =>$where['status']])->order('regtime desc')->select();
            foreach ($cate_data as $k => $v){
                $cate_data[$k]['order_id'] = '';
                $cate_data[$k]['type'] = 'pin';
                $cate_data[$k]['express_charge'] = '';
                $cate_data[$k]['place_address'] = '';
                $cate_data[$k]['target_address'] = '';
                $cate_data[$k]['audio'] = '';
                $cate_data[$k]['audio_length'] = '';
                $cate_data[$k]['status'] = $v["status"];
            }
            $data = array_merge($order_data, $cate_data);
            $msg['data'] = $data;
            $msg['msg'] = "success";
        }
        return json($msg);
    }
    //酒店端订房进行中
    public function get_express_book_order_list()
    {
        $token = request()->request("token");
        $uid = token_decode($token); //酒店
        if (empty($token)){
            $msg['state'] = 0;
            $msg['msg'] = "token:error";
        } else {
            $where['status'] = ['in', '3'];
            $where['express'] = $uid;
            $msg['state'] = 1;
            $fields = 'order_id,type,express_charge,place_address,target_address,audio,audio_length,status';
            $express = Db::table('user')->where('id', $uid)->find();
            $whereIn = Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type');
            $order_data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->whereIn('type', $whereIn)->order('receive_time desc')->select();
            $msg['data'] = $order_data;
            $msg['msg'] = "success";
        }
        return json($msg);
    }
  
    //已完成订单列表【取消拼车把拼车信息放已完成列表中】
    public function get_finish_order_list(){
        $token = request()->request("token");
        $uid = token_decode($token); //司机的
        if (empty($token)){
            $msg['state'] = 0;
            $msg['msg'] = "token:error";
        }else{
            $where['status'] = ['in', '2,9'];
            $where['express'] = $uid;
            $msg['state'] = 1;
            $fields = 'order_id,type,express,express_charge,place_lng,place_lat,place_address,target_lng,target_lat,target_address,audio,audio_length,status';
            $field = 'id as u_p_id,total_count as u_total_count,place_name as u_place_name,target_name as u_target_name,leave_time,count as u_count,type as u_type,price as u_price,status';
            $express =Db::table('user')->where('id', $uid)->find();
            $page = request()->request('page') ? request()->request('page') : 1;
            $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
            $whereIn= Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type');
            $order_data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->whereIn('type', $whereIn)->page($page, $pagesize)->order('complete_time desc')->select();
            foreach ($order_data as $k => $v){
                $order_data[$k]['u_p_id'] = '';
                $order_data[$k]['u_total_count'] = '';
                $order_data[$k]['u_place_name'] = '';
                $order_data[$k]['u_target_name'] = '';
                $order_data[$k]['leave_time'] = '';
                $order_data[$k]['u_count'] = '';
                $order_data[$k]['u_price'] = '';
                $order_data[$k]['status'] = $v["status"];
            }
            //uid要验证下是不是司机的uid 如果是司机的uid则就查询，否则返回空 读取[express_type==1] 
            $cate_data = Db::table("user_pin")->field($field)->where(['uid' => $uid, 'status' =>$where['status']])->page($page, $pagesize)->order('complete_time desc')->select();
            foreach ($cate_data as $k => $v){
                $cate_data[$k]['order_id'] = '';
                $cate_data[$k]['type'] = 'pin';
                $cate_data[$k]['express_charge'] = '';
                $cate_data[$k]['place_address'] = '';
                $cate_data[$k]['target_address'] = '';
                $cate_data[$k]['audio'] = '';
                $cate_data[$k]['audio_length'] = '';
                $cate_data[$k]['status'] = $v['status'];
            }
            $data = array_merge($order_data, $cate_data);
            $msg['data'] = $data;
            $msg['msg'] = "success";
        }
        return json($msg);
    }
    //已完成订房订单列表
    public function get_finish_book_order_list()
    {  
      $token=request()->request("token");
      $uid= token_decode($token);
      if(empty($token)){
            $msg['state'] = 0;
            $msg['msg'] = "token:error";
        }else{
        $where['status'] = ['in', '9'];  
        $where['express'] = $uid;
        $msg['state'] = 1;    
        $fields = 'order_id,type,express,express_charge,place_lng,place_lat,place_address,target_lng,target_lat,target_address,audio,audio_length,status';
        $express =Db::table('user')->where('id', $uid)->find();
        $page = request()->request('page') ? request()->request('page') : 1;
        $pagesize = request()->request('pagesize') ? request()->request('pagesize') : 10;
        $whereIn= Db::table('express_type_order')->where('express_type', $express['express_type'])->value('order_type');
        $order_data = Db::table('order')->field($fields)->where($where)->where(['uid' => ['<>', $uid]])->whereIn('type', $whereIn)->page($page, $pagesize)->order('complete_time desc')->select();
        $msg['data']=$order_data;
        $msg['msg']="success..";
        }
       return json($msg); 
    }
    //司机抢单order_id
    public function grab_order(){
        $token = request()->request("token");
        $uid = token_decode($token); //司机的uid 酒店和司机区别这里还要加个[express_type:主要目的防止酒店抢到司机端的订单]
        $order_id = request()->request('order_id');
        $check = Db::table('user')->where(['id' => $uid, 'isExpress' =>1, 'business' => 1])->count();
        $approve = Db::table("express_check")->where('uid', $uid)->value('status');//防止未审核的接单
          $msg['state'] = 0;
          $msg['data']="";
        if($check == 0||$approve!=1){
            $msg['msg'] = '对不起，您暂时不能接单';
         }else{
            if(empty($order_id)){
                $msg['msg'] = 'order_id is not have';
            }else{
                $order = Db::table('order')->where('order_id', $order_id)->find();
                //如果订单被抢单则表明:express不等于0
                if ($order['express'] !== 0) {
                    $msg['msg'] = '手慢了一步，订单已被抢走啦';
                 }else{
                    $msg['state'] = 1;
                    if($order['type']=="book_a_room"){
                    $cate = Db::table('user')->field("true_name,phone,hotel_address")->where('id', $uid)->find();
                    $data['target_truename'] = $cate['true_name']; //联系人
                    $data['target_phone'] = $cate['phone']; //联系人手机号
                    $data['target_address']=$cate['hotel_address'];//酒店地址
                    $data['express'] = $uid; //司机的uid
                    $data['status'] = 3; //抢单后的status
                    $data['receive_time'] = time();//抢单时间
                    Db::table('order')->where('order_id', $order_id)->update($data);//酒店类型的订单   
                    }else{
                    $cate = Db::table('user')->field("true_name,phone")->where('id', $uid)->find();
                    $data['target_truename'] = $cate['true_name']; //联系人
                    $data['target_phone'] = $cate['phone']; //联系人手机号
                    $data['express'] = $uid; //司机的uid
                    $data['status'] = 3; //抢单后的status
                    $data['receive_time'] = time();//抢单时间
                    Db::table('order')->where('order_id', $order_id)->update($data);//普通类型的订单
                    }
                    //push 给用户
                    push(md5($order['uid']), json_encode(['type' => 1, 'message' => '您的订单已被接单', 'parameters' => $order_id, 'status' =>14]));
                    insert_message($order['uid'], '订单提醒', '您的订单已被接单', 14, $order_id);
                    $msg['data']="";
                    $msg['msg'] = '抢单成功';
                }
            }
        }
        return json($msg);
    }

    //司机取消订单[到新订单列表]
    public function abandon_order(){
        $token = request()->request("token");
        $uid = token_decode($token);
        $order_id = request()->request('order_id');
        $date = date("Y-m-d");
        $check = Db::table("abandon_record")->where(['uid' => $uid, 'date' => $date])->count();
        $msg['state'] = 0;
        $msg['data'] = "";
        $order = Db::table("order")->where('order_id', $order_id)->find();
        if ($order['express'] !== $uid){
            $msg['msg'] = "非法操作";
        }else {
            //接着检测是否超过两次
            if ($check >=3){
                $msg['msg'] = "您今天已经取消了三次,不能再取消";
            }else{
                //如果不是，就执行下面的操作
                $msg['state'] = 1;
                //更新此订单在取消时的情况更改订单状态[type为book_a_room时比较特殊]
               if($order['type']=="book_a_room"){
                  Db::table("order")->where('order_id', $order_id)->update(['status' =>1,"express"=>0,"target_address"=>"","target_phone"=>""]);
                  push(md5($order['uid']), json_encode(['type' => 1, 'message' => '您的订单已被酒店取消', 'parameters' => $order_id, 'status' =>3]));
                  insert_message($order['uid'], '订单提醒', '您的订单已被酒店取消', 5, $order_id);
                  $msg['msg'] = "取消订单";
                }else{
                  Db::table("order")->where('order_id', $order_id)->update(['express' =>'', 'express_get_money' => '','price'=>'','status' => 1]);//订单到新订单
                  Db::table("abandon_record")->insert(['uid' => $uid, 'order_id' => $order_id, 'date' => $date]);
                  push(md5($order['uid']), json_encode(['type' => 1, 'message' => '您的订单被司机取消接单', 'parameters' => $order_id, 'status' => 3]));
                  insert_message($order['uid'], '订单提醒', '您的订单被配送员取消接单',5, $order_id);
                  $msg['msg'] = "取消订单";
                }
                
            }
        }
        return json($msg);
    }

    //计算跑腿费or行程间的费用司机提供价格时用到的数据
     public function count_charge(){
        $token = request()->request("token");
        $uid = token_decode($token);
        $aid = Db::table("express_check")->where("uid", $uid)->value("aid");
        $type = request()->request("type"); //1or2or3
        $data = Db::table("type_price")->field('price1,price2,price3,price4,price5')->where(['aid' => $aid, 'type' => $type])->find();
        if(empty($data)){
          $msg['state']=0;
          $msg['data']=(object)[];
          $msg['msg']="error";   
         }else{
          $msg['state'] = 1;
          $msg['data'] = $data;
          $msg['msg'] = "success!";
         }
        return json($msg);
    }
    
    
    //查看订单详情(叫个车、跑个腿)
      public function get_order_detail(){
        $token = request()->request("token");
        $order_id = request()->request("order_id");
        if (empty($token)) {
            $msg['state'] = 0;
            $msg['msg'] = "error:order_id||token";
        } else {
            $where['order_id'] = $order_id;
            $fields = "order_id,audio,audio_length,image1,image2,image3,place_truename,place_phone,place_address,place_lat,place_lng,target_address,target_lat,target_lng,require_time,express_charge,tip,type,status";
            $order_detail = Db::table("order")->field($fields)->where($where)->find();
            $msg['state'] = 1;
            $msg['data'] = $order_detail;//订单详情
            $msg['msg'] = "success!";
        }
        return json($msg);
    }
//
//    public function test_list() {
//        $u_p_id = request()->request("u_p_id");
//        $msg['state'] = 1;
//        $pin_list = Db::view("order", 'uid,status,place_truename,require_time,place_address,place_lat,place_lng,u_p_id,count')->view("user", 'headimg,phone', 'order.uid=user.id')->view("user_pin", 'price', 'user_pin.id=order.u_p_id')->where("order.u_p_id", $u_p_id)->select();
//        $msg['data']['pin_list'] = $pin_list;
//        return json($msg);
//}
    
    //查看拼车详情以及订单详情
    public function get_pin_detail(){
        $token = request()->request("token");
        $u_p_id = request()->request("u_p_id");
        if (empty($token)) {
            $msg['state'] = 1;
            $msg['msg'] = "error:token";
         }else{
            $where['id'] = $u_p_id;
            $fields = "total_count,place_name,target_name,leave_time,price,status";
            $pin_detail = Db::table("user_pin")->field($fields)->where($where)->find();
           
            if($pin_detail["status"]==3||$pin_detail["status"]==10){
            $pin_list = Db::view("order",'uid,status,order_id,place_truename,require_time,place_address,place_lat,place_lng,u_p_id,count')->view("user", 'headimg,phone', 'order.uid=user.id')->view("user_pin", 'price', 'user_pin.id=order.u_p_id')->where(["order.u_p_id"=>$u_p_id,"order.status"=>['in',"3,7,10"]])->select();
            }elseif($pin_detail['status']==9){
            $pin_list = Db::view("order",'uid,status,order_id,place_truename,require_time,place_address,place_lat,place_lng,u_p_id,count')->view("user", 'headimg,phone', 'order.uid=user.id')->view("user_pin", 'price', 'user_pin.id=order.u_p_id')->where(["order.u_p_id"=>$u_p_id,"order.status"=>9])->select();  
            }elseif($pin_detail["status"]==2){
             $pin_list=[];
            }
            $pin_detail['pin_list']=$pin_list;
            $msg['state'] = 1;
            $msg['data'] = $pin_detail;
            $msg['msg'] = "success!";
        }
        return json($msg);
    }
     /***改变拼车订单状态
      * (其实可以共用一个状态接口:error)
      * ***/
//     public function set_book_order_status(){
//       $token=request()->request("token"); //会话凭证:user:id  
//       $express= token_decode($token);//司机user:id/order:express;
//       $order_id=request()->request("order_id");
//       $where=[];
//       $where['express']=$express;
//       $where['order_id']=$order_id;
//       $status=request()->request("status");
//       $msg['state']=0;
//       $msg['data']="";
//      if(empty($status)){
//          $msg['msg']="error:data";
//      }else{
//          $msg['state']=1;
//          Db::table("order")->where($where)->update(["status"=>$status]);
//          //推送msg
//          $uid=Db::table("order")->where($where)->value("uid");//user:id（用户）
//          if(empty($status)||$status==""){
//             $msg["state"]=0;
//             $msg["msg"]="error:status";
//          }elseif($status== 4){
//             push(md5($uid), json_encode(['type' => 1, 'message' => '司机已到达', 'parameters' => $order_id, 'status' => 8]));
//             insert_message($uid, '订单提醒', '司机已到达', 8, $order_id);
//          }elseif($status == 7){
//             push(md5($uid), json_encode(['type' => 1, 'message' => '正在前往目的地，请系好安全带', 'parameters' => $order_id, 'status' => 10]));
//             insert_message($uid, '订单提醒', '乘客已上车', 10, $order_id);
//         }
//         $msg['msg']="success";
//        }
//        return json($msg);  
//     }
    /**设置拼车状态**/
    public function set_pin_status(){
      $token=request()->request("token");  
      $uid= token_decode($token);  //司机
      $u_p_id=request()->request("u_p_id"); 
      $where=[];
      $where['uid']=$uid;
      $where['id']=$u_p_id;
      $status=request()->request("status");
      $msg['state']=0;
      if(empty($status)||$where==""){
         $msg['msg']="error:data";
         $msg['data']="";
      }else{
        $msg["state"]=1;
        $where["status"]=['in','3,10'];
        $pin_data=Db::table("user_pin")->where($where)->find();
        
       if(empty($pin_data["count"])){
           $msg['state']=0;
           $msg["msg"]="老司机,不要发空车"; 
           $msg['data']="";
          }elseif($pin_data['count']<=$pin_data['total_count']){
            Db::table("user_pin")->where($where)->update(["status"=>$status,'complete_time'=>time()]);
            $data=Db::table("order")->field("uid,express,express_get_money,order_id")->where("u_p_id",$u_p_id)->select();
            foreach($data as $k=>$v){
            $data[$k]['express_id']=$v['express'];//司机uid
            $data[$k]['express_get_money']=$v['express_get_money'];//每个订单中司机应该得到的钱
            $data[$k]['uid']=$v["uid"]; //各自的uid
            $data[$k]['order_id']=$v['order_id'];//各自的order_id
            }
            if($status==10){
             push(md5($data[$k]['uid']), json_encode(['type' => 1, 'message' => '出发啦', 'parameters' =>$data[$k]['order_id'], 'status' =>10]));
             insert_message($data[$k]['uid'], '订单提醒', '乘客上车,准备出发', 10, $data[$k]['order_id']); 
            }else{ //status==9
             Db::table("order")->where(['order_id'=>$data[$k]['order_id']])->update(['status'=>9]);//完成订单
             Db::table("earning")->insert(["order_id"=>$data[$k]['order_id'],'money'=>$data[$k]['express_get_money'],'time'=>time(),"uid"=>$data[$k]['express_id'],"type"=>"express"]);  //插入表中字段
             Db::table("user")->where("id",$data[$k]["express_id"])->setInc("money",$data[$k]['express_get_money']);
             push(md5($data[$k]['uid']), json_encode(['type' => 1, 'message' => '到达目的地', 'parameters' =>$data[$k]['order_id'], 'status' =>10]));
             insert_message($data[$k]['uid'], '订单提醒', '到达目的地', 10, $data[$k]['order_id']); 
           }
         }else{
            $msg['state']=0;
            $msg['data']="";
            $msg['msg']="error:data";
        }
      }
     return json($msg);
    }
    
    /** *
     * 改变订单状态[叫个车、跑个腿]
     */
    public function set_order_status(){
        $token = request()->request("token");
        $express = token_decode($token); //司机id
        $order_id = request()->request("order_id");
        $where = [];
        $where['express'] = $express;
        $where['order_id'] = $order_id;
        $status = request()->request("status");
        $msg['state'] = 0;
        if($status == ''){ 
            $msg['msg'] = "error";
         }else{
            $msg['state'] = 1;
            Db::table('order')->where($where)->update(['status' => $status]);
            //推送msg
            $uid = Db::table('order')->where($where)->value('uid');
            if(empty($status)){
                $msg['state'] = 0;
                $msg['msg'] = "error:status";
            }elseif ($status == 4){
                push(md5($uid), json_encode(['type' => 1, 'message' => '司机已到达', 'parameters' => $order_id, 'status' => 5]));
                insert_message($uid, '订单提醒', '司机已到达', 8, $order_id);
            }elseif ($status == 5){
                push(md5($uid), json_encode(['type' => 1, 'message' => '到达商店', 'parameters' => $order_id, 'status' => 5]));
                insert_message($uid, '订单提醒', '到达商店', 9, $order_id);
             }elseif($status == 6){
                push(md5($uid), json_encode(['type' => 1, 'message' => '采购完成', 'parameters' => $order_id, 'status' => 5]));
                insert_message($uid, '订单提醒', '采购完成', 11, $order_id);
            }elseif ($status == 7){
                push(md5($uid), json_encode(['type' => 1, 'message' => '正在前往目的地，请系好安全带', 'parameters' => $order_id, 'status' => 5]));
                insert_message($uid, '订单提醒', '乘客已上车', 10, $order_id);
            }elseif($status==8){
                push(md5($uid), json_encode(['type' => 1, 'message' => '目的地到达，付款记得好评哦', 'parameters' => $order_id, 'status' => 5]));
                insert_message($uid, '订单提醒', '乘客已上车', 10, $order_id); 
            }
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }
    //变更酒店订单状态并完成酒店订单
    public function set_order_room_status()
   { 
    $token=request()->request("token");    
    $express= token_decode($token);
    $order_id=request()->request("order_id");    
    $where=[];
    $status=request()->request("status");
    $where['express']=$express;
    $where['order_id']=$order_id;
    if(empty($status)){
        $msg['state']=0;
        $msg['msg']="状态为空.";
     }else{
          $msg['state'] = 1;
          Db::table('order')->where($where)->update(['status' => $status,'complete_time'=>time()]);
          $order=Db::table("order")->field("uid,express_get_money")->where($where)->find();
          Db::table("earning")->insert(["order_id"=>$where['order_id'],'money'=>$order['express_get_money'],'time'=>time(),"uid"=>$express,"type"=>"express"]);  //插入表中字段
          Db::table("user")->where("id",$where['express'])->setInc("money",$order['express_get_money']); //酒店帐号的定金入帐
          push(md5($order['uid']), json_encode(['type' => 1, 'message' => '订房完成,联系酒店入住', 'parameters' => $order_id, 'status' => 10]));
          insert_message($order['uid'], '订单提醒', '订房完成', 10, $order_id);
          $msg['msg']="success";
        }
        return json($msg);
    }
    /*     * *
     * 司机更新订单价格
     * * */
    public function update_price_to_order(){
        $token = request()->request("token");
        $uid = token_decode($token);
        $order_id = request()->request("order_id");
        $express_charge = request()->request("express_charge"); //固定可选的价格
        if(empty($express_charge)){
            $msg['state'] = 0;
            $msg['data']=[];
            $msg['msg'] = "error:ex-char";
         }else{
            $order = Db::table("order")->where(['express' => $uid, 'order_id' => $order_id])->find();
            $express_get_money="";//司机的钱
            $price="";//订单应付钱
            if($order['status'] == ""){
                $msg['state'] = 0;
                $msg['data']=(object)[];
                $msg['msg'] = "order:error";
            }else{
                if($order['tip']===0){
                  $price=$express_charge;//要付价格
                  $express_get_money=$express_charge;//司机钱
                }
                $price=$express_charge + $order['tip'];//要付价格
                $express_get_money=$express_charge+$order['tip'];//司机钱
            }
            //更新价格
            Db::table("order")->where("order_id", $order_id)->update(['price' => $price, 'express_charge' => $express_charge,'express_get_money'=>$express_get_money,'status'=>8]);
            push(md5($order['uid']), json_encode(['type' => 1, 'message' => '目的地到达,请支付', 'parameters' => $order_id, 'status' => 12]));
            insert_message($order['uid'], '订单提醒', '需要您支付订单', 12, $order_id);
            $msg['state'] = 1;
            $msg['msg'] = "success";
        }
        return json($msg);
    }

    //司机取消拼车
    public function abandon_pin(){
        $token = request()->request("token");
        $uid = token_decode($token); //司机id
        $u_p_id = request()->request("u_p_id");
       //思路:判断拼车表中count是否有值，有值就不能取消。取消的话，将拼单迁移到已完成里
        $count = Db::table("user_pin")->where(['uid' => $uid, 'id'=>$u_p_id])->value("count");
        if ($count >0){
            $msg['state'] =0;
            $msg['data']="";
            $msg['msg'] = "拼单有人,联系用户取消后再取消拼单";
        }else{
            $msg['state'] = 1;
            $msg['data']="";
            Db::table("user_pin")->where(["id" => $u_p_id])->update(['status'=>2,'count'=>0]);//取消拼车单
            $msg['msg'] = "success;";
        }
        return json($msg);
    }
    
 
}
